package com.weiyuanstudio.nextstep.service.database;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.weiyuanstudio.nextstep.dto.database.AllTabColumn;
import com.weiyuanstudio.nextstep.persistence.entity.dbm.DatabaseBaselineTableColumn;
import com.weiyuanstudio.nextstep.persistence.entity.dbm.DatabaseBaselineVersion;
import com.weiyuanstudio.nextstep.persistence.repository.database.DatabaseBaselineTableColumnRepository;
import com.weiyuanstudio.nextstep.persistence.repository.database.DatabaseBaselineVersionRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class BaselineService {
    @Autowired
    DatabaseBaselineVersionRepository versionRepository;
    @Autowired
    DatabaseBaselineTableColumnRepository columnRepository;

    @Transactional
    public void saveBaselineJson(String json) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode root = objectMapper.readTree(json);
        int size = root.size();

        List<DatabaseBaselineTableColumn> temp = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            JsonNode node = root.get(i);
            AllTabColumn allTabColumn = objectMapper.treeToValue(node, AllTabColumn.class);
            DatabaseBaselineTableColumn tableColumn = allTabColumn.convertToEntity();
            temp.add(tableColumn);
        }

        DatabaseBaselineVersion version = versionRepository.save(new DatabaseBaselineVersion());
        Long id = version.getId();

        temp.forEach(item -> item.setBaselineVersionId(id));

        columnRepository.saveAll(temp);
    }
}
